const mongoose = require("mongoose");
const redis = require("./redis");
const { log } = require("./utils");
const env = require("./env");

// 初始化权限
const initAcl = async () => {
	try {
		const Meta = mongoose.model("Meta");
		const metas = await Meta.find({});
		metas.map(item => item.roles.push(env.rootUser.roleCode));
		try {
			let rlt = await redis.set(env.redis.aclKey, JSON.stringify({ metas }));
			if (rlt === "OK") {
				log("blue", "Acl 初始化成功！");
			} else {
				log("red", "Acl 初始化失败！");
			}
		} catch (error) {
			log("red", `读取redis错误: ${error}`);
		}
	} catch (error) {
		log("red", `[初始化权限]查询权限或角色出错：${error}`);
	}
};
// 检验权限
const checkPermission = permission => {
	return async (req, res, next) => {
		try {
			let rlt = await redis.get(env.redis.aclKey);
			let role = (req.user && req.user.role) ? req.user.role.code : null;
			if (!role) return next(new Error("没有登陆!"));
			rlt = JSON.parse(rlt);
			let metas = rlt.metas.filter(item => item.permission === permission);
			if (metas[0] && metas[0].roles.includes(role)) return next();
			return next(new Error(`没有${metas[0] && metas[0].permission_des ? metas[0].permission_des : ""}权限!`));
		} catch (err) {
			log("red", `读取redis错误: ${err}`);
			return next(new Error("(权限)读取redis错误!"));
		}
	};
};

module.exports = {
	initAcl,
	checkPermission
};

// 生成权限 v1
// [
// 	{
// 		roles:['guest'],
// 		allows:[
// 			{resources:'blogs', permissions:'get'},
// 			{resources:['forums', 'news'], permissions:['get', 'put', 'delete']}
// 		]
// 	},
// 	{
// 		roles:['admin'],
// 		allows:[
// 			{resources:'cash', permissions:['sell', 'exchange']},
// 			{resources:['account', 'deposit'], permissions:['put', 'delete']}
// 		]
// 	}
// ]
// const genPermissions = async () => {
// const Meta = mongoose.model("Meta");
// const Role = mongoose.model("Role");
// let [metas, roles] = [null, null];
// try {
//   [metas, roles] = await Promise.all([Meta.find({}), Role.find({})]);
// } catch (err) {
//   log("red", `[初始化权限]查询权限或角色出错：${err}`);
// }
// let [roleObj, permissions, rootRole] = [{}, [], null];
// roles.forEach(item => {
//   //增加超级管理员
//   if (item.code === env.rootUser.roleCode) rootRole = item;
//   roleObj[item.code] = {
//     code: item.code,
//     data: []
//   };
// });
// metas.forEach(item => {
//   // item.roles.push(rootRole.code);
//   let roles = item.roles;
//   roles.forEach(async (im, i) => {
//     if (!roleObj[im]) {
//       let rls = Array.from(item.roles);
//       rls = rls.filter(item => item !== im && item !== env.rootUser.roleCode);
//       const cond = {
//         roles: rls
//       };
//       await Meta.updateOne({ _id: item._id }, cond);
//     } else {
//       roleObj[im].data.push({
//         resources: item.resource,
//         permissions: item.permission
//       });
//     }
//   });
// });
// Object.keys(roleObj).forEach(role => {
//   permissions.push({
//     roles: [roleObj[role].code],
//     allows: roleObj[role].data
//   });
// });
//   return permissions;
// }


